package com.fifth.apartment.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fifth.apartment.entity.Setmeal;
import com.fifth.apartment.mapper.SetmealMapper;
import com.fifth.apartment.service.SetmealService;
import com.fifth.apartment.utils.OssUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * TODO
 *
 * @author Dao
 * @since 2024/7/7
 */
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealMapper mapper;

    //阿里云上传
    public String uploadByAliyun(MultipartFile imgFile){
        if(imgFile!=null){
            // Endpoint以上海为例，其它Region请按实际情况填写。
            String endpoint = OssUtil.EDNPOINT;
            String accessKeyId = OssUtil.ACCESS_KEY_ID;
            String accessKeySecret = OssUtil.SECRECT;
            String bucketName = OssUtil.BUCKET;

            try {
                //创建OSSClient实例
                OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

                //TODO 获取上传文件的流对象 inputStream
                InputStream inputStream = imgFile.getInputStream();

                //TODO 处理上传文件名称 fileName
                String oldName = imgFile.getOriginalFilename();
                if(StringUtils.hasLength(oldName)){
                    String newName = UUID.randomUUID()+oldName;
                    String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
                    String fileName = date +"/"+ newName;  //  2021/05/06/0a4954938c5e488886924a01eca95ebd1.png

                    //调用方法实现上传
                    ossClient.putObject(bucketName, fileName, inputStream);
                    //关闭OSSClient
                    ossClient.shutdown();

                    //TODO 返回上传之后文件路径 url
                    //格式例如：https://igeek-health.oss-cn-shanghai.aliyuncs.com/2021/05/06/0a4954938c5e488886924a01eca95ebd1.png
                    String url = "https://"+bucketName+"."+endpoint+"/"+fileName;

                    return url;
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


}
